<?php

namespace app\mp\admin;

use app\common\service\GeneralMaterial as GeneralMaterialService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\Stock as StockService;
use app\common\service\StockLog as StockLogService;
use app\common\service\StockUse as StockUseService;
use app\system\admin\Admin;
use think\Db;
use app\common\service\Order as OrderService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\OrderOutgo;

/**
 * 外发管理》委外对帐  与 外发管理》委外结算
 * @author zhuguosen 905502314@qq.com
 * @date 2021/12/8
 * @package app\mp\admin
 */
class OutCheckOrder extends Admin
{
    /**
     * @var \app\common\service\OrderOutgo
     */
    protected $orderOutgoServer;

    public function initialize()
    {
        parent::initialize();
        $this->orderOutgoServer = new OrderOutgo();
    }

    /**
     * 外发管理》委外对帐
     * @date 2021/12/27
     * @author zhuguosen 905502314@qq.com
     */
    public function index()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            $where = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $tab_status = $this->request->param('status/d', 1);

            $where = $this->_where_index($where);
            $export = $this->request->param('export/d', 0);
            if ($export) {
                set_time_limit(0);
                ini_set('memory_limit', '1024M');
                $page = 1;
                $limit = 99999;
            }
            switch ($tab_status) {
                case 1:
                case 2://总数：<span title="总下单数">{{ d.osStat.order_count }}</span>/<span title="总裁床数">{{ d.osStat.shicai_count }}</span>/<span title="总车间数">{{ d.osStat.jiaohuo_count }}</span>/<span title="总后整数">{{ d.osStat.jiaohuo_tail_count }}</span>/<span title="总打包数">{{ d.osStat.delivery_count }}</span>/<span title="总出货数">{{ d.osStat.daohuo_count }}</span>
                    $order = "ooor.update_time desc";
                    $list = db('order_outgo_order ooor')
                        ->field('ooor.* ,o.sku ,o.is_auto_import ,oext.cost_little as order_cost_little
                        ,s.pic,s.ori_pic
                ,ft.name as ft_name ,g.name as ft_group_name
                ,o.tail_over_time
                ,u.username as admin_username
                ')
                        ->join('order o', "o.id=ooor.order_id", 'left')
                        ->join('order_ext oext', "o.id=oext.order_id", 'left')
                        ->join('sku s', "o.sku=s.sku", 'left')
                        ->join('factory ft', "ft.id=ooor.factory_id", 'left')
                        ->join('wx_group g', 'g.id=ooor.factory_child_id', 'left')
                        ->join('system_user u', 'ooor.admin_id=u.id', 'left')
                        ->where($where)
                        ->page($page)->limit($limit)->orderRaw($order)
                        ->select();
                    $count = db('order_outgo_order ooor')
                        ->join('order o', "o.id=ooor.order_id", 'left')
                        ->join('factory ft', "ft.id=ooor.factory_id", 'left')
                        ->join('wx_group g', 'g.id=ooor.factory_child_id', 'left')
                        ->where($where)
                        ->count();
                    $list = $this->_deal_with_index($list);
                    break;
                case 3:
                    $factory_ids = $this->request->param('factory_ids/s', '');
                    $where = [
                        ['ogp.status', '=', 1130],
                    ];
                    if (trim($factory_ids) != '') {
                        $where[] = ['ogp.factory_child_id', 'in', $factory_ids];
                    }
                    $list = db('order_outgo_order_group ogp')
                        ->field('ogp.*,ogp.create_time as ogp_create_time
                         ,ft.name as ft_name ,g.name as ft_group_name
                         ,count(ooor.id) as order_count
                         ,sum(ooor.caichuang_t_strip_price) as sum_caichuang_t_strip_price
                         ,sum(ooor.after_return_price) as sum_after_return_price
                         ,sum(ooor.other_cut_payment) as sum_other_cut_payment
                          ,sum(ooor.price_all) as sum_price_all
                        ')
                        ->join('order_outgo_order ooor', "ogp.id=ooor.order_outgo_order_group_id", 'left')
                        ->join('order o', "o.id=ooor.order_id", 'left')
                        ->join('factory ft', "ft.id=ooor.factory_id", 'left')
                        ->join('wx_group g', 'g.id=ooor.factory_child_id', 'left')
                        ->where($where)
                        ->page($page)->limit($limit)
                        ->group('ogp.id')
                        ->orderRaw('ogp.id desc')->select();
                    foreach ($list as $k => $v) {
                        if (intval($v['id']) == 0) {
                            unset($list[$k]);
                            continue;
                        }
                        $list[$k]['ogp_create_time'] = date('Y-m-d H:i:s', $list[$k]['ogp_create_time']);
                        //应付金额
                        $list[$k]['payable'] = sprintf("%.2f", $v['sum_price_all'] - $v['sum_after_return_price'] - $v['sum_other_cut_payment'] - $v['sum_caichuang_t_strip_price']);
                    }
                    $count = db('order_outgo_order_group ogp')
                        ->join('order_outgo_order ooor', "ogp.id=ooor.order_outgo_order_group_id", 'left')
                        ->join('order o', "o.id=ooor.order_id", 'left')
                        ->join('factory ft', "ft.id=ooor.factory_id", 'left')
                        ->join('wx_group g', 'g.id=ooor.factory_child_id', 'left')
                        ->where($where)->group('ogp.id')->count();
                    break;
                case 4:
                    $where = [
                        ['ogp.status', '=', 1140],
                    ];
                    $list = db('order_outgo_order_group ogp')
                        ->field('ogp.*
                         ,ft.name as ft_name ,g.name as ft_group_name
                         ,count(ooor.id) as order_count
                         ,sum(ooor.caichuang_t_strip_price) as sum_caichuang_t_strip_price
                         ,sum(ooor.after_return_price) as sum_after_return_price
                         ,sum(ooor.other_cut_payment) as sum_other_cut_payment
                          ,sum(ooor.price_all) as sum_price_all
                         ,su.username
                        ')
                        ->join('order_outgo_order ooor', "ogp.id=ooor.order_outgo_order_group_id", 'left')
                        ->join('order o', "o.id=ooor.order_id", 'left')
                        ->join('factory ft', "ft.id=ooor.factory_id", 'left')
                        ->join('group g', 'g.id=ooor.factory_child_id', 'left')
                        ->join('system_user su', 'su.id=ogp.admin_id_submit', 'left')
                        ->where($where)
                        ->page($page)->limit($limit)->orderRaw('ogp.id desc')
                        ->group('ogp.id desc')
                        ->select();
                    foreach ($list as $k => $v) {
                        if (intval($v['id']) == 0) {
                            unset($list[$k]);
                            continue;
                        }
                        $list[$k]['time_submit'] = date('Y-m-d H:i:s', $list[$k]['time_submit']);
                        $list[$k]['status_account'] = '待结算';
                        switch ($v['status']) {
                            case '1200':
                                $list[$k]['status_account'] = '已结算';
                                break;
                        }
                        //应付金额
                        $list[$k]['payable'] = sprintf("%.2f", $v['sum_price_all'] - $v['sum_after_return_price'] - $v['sum_other_cut_payment']);
                    }
                    $count = db('order_outgo_order_group ogp')
                        ->join('order_outgo_order ooor', "ogp.id=ooor.order_outgo_order_group_id", 'left')
                        ->join('order o', "o.id=ooor.order_id", 'left')
                        ->join('factory ft', "ft.id=ooor.factory_id", 'left')
                        ->join('group g', 'g.id=ooor.factory_child_id', 'left')
                        ->join('system_user su', 'su.id=ogp.admin_id_submit', 'left')
                        ->where($where)->group('ogp.id desc')->count();
                    break;
            }
            if ($export) {
                $this->_exportXls('委外对帐-' . date('YmdHis'), $list);
                exit;
            }
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list,
                'count' => $count,
                'status' => $tab_status,
                'statData' => $this->_get_statData(),
            ];
            return json($result);
        }
        $statData = $this->_get_statData();
        $assign = [
            'status' => 1,
            'statData' => $statData,
            'group_out_type_select' => [
                0 => '请选择',
                2 => '车间',
                3 => '尾部',
                4 => '专机',
            ],
            'status_account_select' => [
                0 => '请选择',
                1140 => '待结算',
                1200 => '已结算',
            ],
            'factory_ids' => $this->_factiory_xm_select(),
        ];
        return $this->assign($assign)->fetch();
    }

    private function _get_statData()
    {
        $where_temp = [];
        //订单加一级
        order_level($where_temp, 'o.');
        $statData = [
            1 => db('order_outgo_order ooor')
                ->join('order o', "ooor.order_id=o.id", 'left')
                ->where([
                    ['ooor.status', 'in', [1101, 1102]],
                    ['ooor.data_version', '>', 0],
                    ['o.status', '=', 2],
                ])
                ->where($where_temp)
                ->count(),
            2 => db('order_outgo_order ooor')
                ->join('order o', "ooor.order_id=o.id", 'left')
                ->where([
                    ['ooor.status', '=', 1102],
                    ['ooor.data_version', '>', 0],
                    ['o.status', '=', 2],
                ])
                ->where($where_temp)
                ->count(),
            3 => db('order_outgo_order ooor')
                ->join('order o', "ooor.order_id=o.id", 'left')
                ->where([
                    ['ooor.status', '=', 1120],
                    ['ooor.data_version', '>', 0],
                    ['o.status', '=', 2],
                ])
                ->where($where_temp)
                ->count(),
            4 => db('order_outgo_order_group ogp')
                ->join('order_outgo_order ooor', "ooor.order_outgo_order_group_id=ogp.id", 'left')
                ->join('order o', "ooor.order_id=o.id", 'left')
                ->where([
                    ['ogp.status', '=', 1130]
                ])
                ->where($where_temp)
                ->group('ogp.id')
                ->count(),
            5 => db('order_outgo_order_group ogp')
                ->join('order_outgo_order ooor', "ooor.order_outgo_order_group_id=ogp.id", 'left')
                ->join('order o', "ooor.order_id=o.id", 'left')
                ->where([
                    ['ogp.status', '=', 1140]
                ])
                ->where($where_temp)
                ->group('ogp.id')
                ->count(),
        ];
        return $statData;
    }

    // 获取委外工厂信息
    private function _factiory_xm_select()
    {
        $list = db('factory f')
            ->field('f.id as p_id ,f.name as p_name
            ,g.*
            ')
            ->join('wx_group g', 'g.factory_id=f.id', 'left')
            ->where([
                ['f.type', '=', 1],
                ['f.status', '=', 1],
            ])
            ->select();
        $p = [];
        foreach ($list as $k => $v) {
            $p[$v['p_id']] = $v;
        }
        $res = [];
        foreach ($p as $k => $v) {
            $temp_p = [
                'name' => $v['p_name'],
                'value' => 10000 + $v['p_id'],
                'children' => [],
            ];
            foreach ($list as $k2 => $v2) {
                if ($v2['p_id'] == $v['p_id']) {
                    $temp_p['children'][] = [
                        'name' => $v2['name'],
                        'value' => $v2['id'],
                    ];
                }
            }
            $res[] = $temp_p;
        }
        return $res;
    }

    private function _where_index($where, $delwhere = [])
    {
        $where[] = ['ooor.factory_id', '>', 0];
        $where[] = ['ooor.data_version', '>', 0];
        $where[] = ['o.status', '=', 2];
        //订单加一级
        order_level($where, 'o.');
        $tab_status = $this->request->param('status/d', 1);
        if (isset($delwhere['status'])) {
            $tab_status = 0;
        }
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $sku = $this->request->param('sku/s', '');
        $createDateRange = $this->request->param('create_date_range/s');
        $overDateRange = $this->request->param('over_date_range/s');
        $isAutoImport = $this->request->param('is_auto_import/d', 0);
        $group_out_type = $this->request->param('group_out_type/d', 0);
        $factory_ids = $this->request->param('factory_ids/s', '');
        if ($tab_status == 1) {
            $where[] = ['ooor.status', 'in', [1101, 1102]];
        }
        if ($tab_status == 2) {
            $where[] = ['ooor.status', '=', 1120];
        }
        if ($clientOrdernum != '') {
            $where[] = ['o.client_ordernum', 'like', "%" . $clientOrdernum . "%"];
        }
        if ($sku != '') {
            $where[] = ['o.sku', 'like', "%" . $sku . "%"];
        }
        if ($createDateRange != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
            $where[] = ['o.create_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($overDateRange != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $overDateRange));
            $where[] = ['o.over_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($isAutoImport > 0) {
            $where[] = ['o.is_auto_import', '=', $isAutoImport];
        }
        if ($group_out_type > 0) {
            $where[] = ['ooor.group_out_type', 'like', "%" . $group_out_type . "%"];
        }
        if (trim($factory_ids) != '') {
            $where[] = ['ooor.factory_child_id', 'in', $factory_ids];
        }
        return $where;
    }

    private function _deal_with_index($list)
    {
        foreach ($list as $k => $v) {
            $list[$k]['tail_over_time'] = $v['tail_over_time'] > 0 ? date('Y-m-d H:i:s', $v['tail_over_time']) : '';
            //来源
            $list[$k]['is_auto_import_name'] = arrayGet(config('mimo.order_from'), $v['is_auto_import'], '');
            $list[$k]['remark'] = $v['status'] == 1102 ? '驳回' : '';
            $osList = (new OrderSizeService())->getListByOrderId($v['order_id']);
            ////总数：<span title="总下单数">{{ d.osStat.order_count }}</span>/<span title="总裁床数">{{ d.osStat.shicai_count }}</span>/<span title="总车间数">{{ d.osStat.jiaohuo_count }}</span>/<span title="总后整数">{{ d.osStat.jiaohuo_tail_count }}</span>/<span title="总打包数">{{ d.osStat.delivery_count }}</span>/<span title="总出货数">{{ d.osStat.daohuo_count }}</span>
            $list[$k]['sum_shicai_count'] = array_sum(array_column($osList, 'shicai_count'));
            $list[$k]['sum_jiaohuo_count'] = array_sum(array_column($osList, 'jiaohuo_count'));
            $list[$k]['sum_jiaohuo_tail_count'] = array_sum(array_column($osList, 'jiaohuo_tail_count'));
            $sum_store_count = array_sum(array_column($osList, 'store_count'));
            intval($v['sum_store_count']) > 0 && $sum_store_count = $v['sum_store_count'];
            $list[$k]['sum_store_count'] = $sum_store_count;
            //差异数
            $list[$k]['chayi_num'] = $list[$k]['sum_store_count'] - $list[$k]['sum_shicai_count'];

            //状态
            $list[$k]['status_txt'] = '未审核';
            switch ($v['status']) {
                case 1120:
                case 1130:
                    $list[$k]['status_txt'] = '已审核';
                    break;
                case 1140:
                    $list[$k]['status_txt'] = '已提交';
                    break;
                case 1200:
                    $list[$k]['status_txt'] = '已付款';
                    break;
            }
            $this->orderOutgoServer->_deal_with_index_m0($list[$k]);
        }
        return $list;
    }

    /**
     * 修改字段
     * @date 2021/12/25
     * @author zhuguosen 905502314@qq.com
     */
    public function editUnit()
    {
        $param = [
            'id' => $this->request->param('id/d', 0),
            'field' => $this->request->param('field/s', 0),
            'value' => $this->request->param('value/s', 0),
        ];
        switch ($param['field']) {//参数处理
            case 'confiscation_num':
            case 'caichuang_t_strip_price':
            case 'sum_store_count':
            case 'sum_stock_in':
            case 'other_cut_payment':
            case 'after_return_price':
                $param['value'] = floatval($param['value']);
                if ($param['value'] < 0) {
                    return $this->Json(11, '修改失败,数值不能小于0');
                }
                break;
            default:
                break;
        }
        switch ($param['field']) {
            case 'after_return_price':
                $order_outgo_order_info = db('order_outgo_order')->where([
                    ['id', '=', $param['id']],
                    ['status', 'in', [1101, 1102]],
                ])->find();
                if (!isset($order_outgo_order_info['id'])) {
                    return $this->Json(10, '修改失败');
                }
                $info = db('order o')
                    ->field('o.id,o.client_ordernum 
                ,g.unit_time_price
                ,oot.id as oot_id
                ,oot.after_return_reason,oot.after_return_num,oot.after_return_time
                ')
                    ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                    ->join('factory ft', "ft.id=o.factory_id", 'left')
                    ->join('wx_group g', 'oot.group_id=g.id', 'left')
                    ->where([
                        ['o.id', '=', $order_outgo_order_info['order_id']],
                    ])->find();
                Db::startTrans();
                try {
                    //2,业务->修改表 wx_order_outgo order_outgo_order
                    $temp = db('order_outgo')->where([
                        ['id', '=', $info['oot_id']],
                    ])->update([
                        'after_return_time' => sprintf("%.3f", $param['value'] / $info['unit_time_price']),
                    ]);
                    if ($temp != 1) {
                        Db::rollback();
                        return $this->json(11, '设置失败');
                    }
                    $temp2 = db('order_outgo_order')->where([
                        ['id', '=', $param['id']],
                    ])->update([
                        'after_return_time' => sprintf("%.3f", $param['value'] / $info['unit_time_price']),
                        'after_return_price' => $param['value'],
                        'unit_time_price' => $info['unit_time_price'],
                        'after_return_num' => $info['after_return_num'],
                    ]);
                    if ($temp2 != 1) {
                        Db::rollback();
                        return $this->json(12, '设置失败');
                    }
                    //5,成本->暂无
                    //6,财务->暂无
                    //7,经验->暂无
                    Db::commit();
                    return $this->json(1, '保存成功');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->json(13, '设置失败');
                }
                break;
            default:
                $temp = db('order_outgo_order')->where([
                    ['id', '=', $param['id']],
                    ['status', 'in', [1101, 1102]],
                ])->update([
                    $param['field'] => $param['value'],
                ]);
                if ($temp == 1) {
                    return $this->Json(1, '修改成功', $temp);
                }
                return $this->Json(10, '修改失败', $temp);
                break;
        }
    }

    /**
     * 审核 ，驳回 等动作
     * @date 2021/12/25
     * @author zhuguosen 905502314@qq.com
     */
    public function check()
    {
        //1,参数处理
        $status = $this->request->param('status/d', 0);
        $ids = $this->request->param('id', []);
        $type = $this->request->param('type/s', '');
        $stall_feed_id = $this->request->param('stall_feed_id/d', 0);
        foreach ($ids as $k => $id) {
            $ids[$k] = intval($id);
        }
        $res = $this->orderOutgoServer->outCheckOrder_check([
            'ids' => $ids,
            'status' => $status,
            'type' => $type,
            'stall_feed_id' => $stall_feed_id,
            'auto_admin_id' => 1,
        ]);
        return $this->Json($res['code'], $res['msg'], $res['data']);
    }

    /**
     * 生成帐单
     * @date 2021/12/25
     * @author zhuguosen 905502314@qq.com
     */
    public function makeBill()
    {
        //1,参数处理
        $ids = $this->request->param('id', []);
        foreach ($ids as $k => $id) {
            $ids[$k] = intval($id);
        }
        Db::startTrans();
        try {
            //2,业务->wx_order_outgo_order_group表修改
            $order_outgo_order_group = [
//                [
//                    'id' => 0,
//                    'order_outgo_order_group_id' => 0,
//                ],
            ];
            $grSelect = db('order_outgo_order odr')
                ->field('odr.id ,odr.factory_id ,odr.factory_child_id
                ,ogp.status as ogp_status,ogp.id as ogp_id
                ')
                ->join('order_outgo_order_group ogp', "odr.factory_id=ogp.factory_id and odr.factory_child_id=ogp.factory_child_id", 'left')
                ->where([
                    ['odr.id', 'in', $ids],
                    ['odr.status', '=', 1120],
                ])->select();
            if (count($grSelect) == 0) {
                Db::rollback();
                return $this->Json(10, '失败');
            }
            $in_temp = [];
            foreach ($grSelect as $k2 => $v2) {
                if ($v2['ogp_status'] == 1130) {
                    $order_outgo_order_group[$v2['id']]['id'] = $v2['id'];
                    $order_outgo_order_group[$v2['id']]['order_outgo_order_group_id'] = $v2['ogp_id'];
                } else {
                    //添加 order_outgo_order_group 行
                    if (isset($in_temp[$v2['factory_id']][$v2['factory_child_id']])) {
                        $temp = $in_temp[$v2['factory_id']][$v2['factory_child_id']];
                    } else {
                        $temp = db('order_outgo_order_group')->insertGetId([
                            'status' => 1130,
                            'factory_id' => $v2['factory_id'],
                            'factory_child_id' => $v2['factory_child_id'],
                            'create_time' => time(),
                            'update_time' => time(),
                            'admin_id' => ADMIN_ID,
                        ]);
                        if ($temp <= 0) {
                            Db::rollback();
                            return $this->Json(11, '失败');
                        }
                    }
                    $order_outgo_order_group[$v2['id']]['id'] = $v2['id'];
                    $order_outgo_order_group[$v2['id']]['order_outgo_order_group_id'] = $temp;
                    //标识已经有数据
                    $in_temp[$v2['factory_id']][$v2['factory_child_id']] = $temp;
                }
            }
            //3,业务->order_outgo_order表修改
            foreach ($order_outgo_order_group as $k => $v) {
                $temp = db('order_outgo_order')->where([
                    ['id', '=', $v['id']],
                    ['status', '=', 1120],
                ])->update([
                    'status' => 1130,
                    'order_outgo_order_group_id' => $v['order_outgo_order_group_id'],
                    'update_time' => time(),
                    'admin_id' => ADMIN_ID,
                    'admin_id_1130' => ADMIN_ID,
                    'time_update_1130' => time(),
                ]);
                if ($temp != 1) {
                    Db::rollback();
                    return $this->Json(12, '失败', $temp);
                }
            }
            //4,业务log->暂无
            //5,成本->暂无
            //6,财务->暂无
            //7,经验->暂无
            Db::commit();
            return $this->json(1, '成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->json(100, '失败');
        }
    }

    /**
     * 提交结算
     * @date 2021/12/25
     * @author zhuguosen 905502314@qq.com
     */
    public function submitPayment()
    {
        //1,参数处理
        $ids = $this->request->param('id', []);
        foreach ($ids as $k => $id) {
            $ids[$k] = intval($id);
        }
        Db::startTrans();
        try {
            //2,业务->wx_order_outgo_order_group表修改
            $temp = db('order_outgo_order_group')
                ->where([
                    ['id', 'in', $ids],
                    ['status', '=', 1130],
                ])->update([
                    'status' => 1140,
                    'time_submit' => time(),
                    'admin_id' => ADMIN_ID,
                    'admin_id_submit' => ADMIN_ID,
                    'update_time' => time(),
                ]);
            if ($temp != count($ids)) {
                Db::rollback();
                return $this->Json(10, '失败');
            }
            //3,业务->order_outgo_order表修改
            $count = db('order_outgo_order')->where([
                ['order_outgo_order_group_id', 'in', $ids],
                ['status', '=', 1130],
            ])->count();
            $temp = db('order_outgo_order')->where([
                ['order_outgo_order_group_id', 'in', $ids],
                ['status', '=', 1130],
            ])->update([
                'status' => 1140,
                'admin_id' => ADMIN_ID,
                'update_time' => time(),
                'admin_id_1140' => ADMIN_ID,
                'time_update_1140' => time(),
            ]);
            if ($temp != $count) {
                Db::rollback();
                return $this->Json(11, '失败', $temp);
            }
            //4,业务log->暂无
            //5,成本->暂无
            //6,财务->暂无
            //7,经验->暂无
            Db::commit();
            return $this->json(1, '成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->json(100, '失败');
        }
    }

    /**
     * 查看 帐单明细--可返审，驳回，结束时不可操作
     * @date 2021/12/25
     * @author zhuguosen 905502314@qq.com
     */
    public function billList()
    {
        $stall_feed_id = $this->request->param('stall_feed_id/d', 0);
        $status_type = $this->request->param('status_type/d', 0);
        $status_real = $this->request->param('status_real/d', 0);
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            $where = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $tab_status = $this->request->param('status/d', 1);

            $where = $this->_where_index($where, ['status' => 1,]);
            $export = $this->request->param('export/d', 0);
            if ($export) {
                set_time_limit(0);
                ini_set('memory_limit', '1024M');
                $page = 1;
                $limit = 99999;
            }
            $where[] = ['ogp.id', '=', $stall_feed_id];
            $status_real > 0 && $where[] = ['ooor.status', '=', $status_real];
            $order = "ooor.update_time desc";
            $list = db('order_outgo_order ooor')
                ->field('ooor.* ,o.sku ,o.is_auto_import,oext.cost_little as order_cost_little
                 ,s.pic,s.ori_pic
                ,ft.name as ft_name ,g.name as ft_group_name
                ,o.tail_over_time
                 ,u.username as admin_username
                ')
                ->join('order o', "o.id=ooor.order_id", 'left')
                ->join('order_ext oext', "o.id=oext.order_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('factory ft', "ft.id=ooor.factory_id", 'left')
                ->join('group g', 'g.id=ooor.factory_child_id', 'left')
                ->join('order_outgo_order_group ogp', "ogp.id=ooor.order_outgo_order_group_id", 'left')
                ->join('system_user u', 'ooor.admin_id=u.id', 'left')
                ->where($where)
                ->page($page)->limit($limit)->orderRaw($order)
                ->select();
            $count = db('order_outgo_order ooor')
                ->join('order o', "o.id=ooor.order_id", 'left')
                ->join('order_ext oext', "o.id=oext.order_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('factory ft', "ft.id=ooor.factory_id", 'left')
                ->join('group g', 'g.id=ooor.factory_child_id', 'left')
                ->join('order_outgo_order_group ogp', "ogp.id=ooor.order_outgo_order_group_id", 'left')
                ->where($where)->count();
            $list = $this->_deal_with_index($list);
            if ($export) {
                $this->_exportXls('委外对帐-' . date('YmdHis'), $list);
                exit;
            }
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list,
                'count' => $count,
                'status' => $tab_status,
                'statData' => [
                    1 => 20,
                    2 => 2,
                    3 => 30,
                    4 => 4,
                    5 => 5,
                ],
            ];
            return json($result);
        }
        $where = [];
        $where[] = ['ogp.id', '=', $stall_feed_id];
        $where[] = ['ogp.status', '<=', 1200];
        //订单加一级
        order_level($where, 'o.');
        $ogp_info = db('order_outgo_order_group ogp')
            ->field('ogp.*,ogp.create_time as ogp_create_time
                         ,ft.name as ft_name ,g.name as ft_group_name
                         ,count(ooor.id) as order_count
                         ,sum(ooor.after_return_price) as sum_after_return_price
                         ,sum(ooor.other_cut_payment) as sum_other_cut_payment
                          ,sum(ooor.price_all) as sum_price_all
                        ')
            ->join('order_outgo_order ooor', "ogp.id=ooor.order_outgo_order_group_id", 'left')
            ->join('order o', "o.id=ooor.order_id", 'left')
            ->join('factory ft', "ft.id=ooor.factory_id", 'left')
            ->join('wx_group g', 'g.id=ooor.factory_child_id', 'left')
            ->where($where)
            ->group('ogp.id')
            ->find();
        //应付金额
        $ogp_info['payable'] = sprintf("%.2f", $ogp_info['sum_price_all'] - $ogp_info['sum_after_return_price'] - $ogp_info['sum_other_cut_payment']);
        $assign = [
            'stall_feed_id' => $stall_feed_id,
            'status_type' => $status_type,
            'status_real' => $status_real,
            'ogp_info' => $ogp_info,
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     * 外发管理》委外结算
     * @date 2021/12/27
     * @author zhuguosen 905502314@qq.com
     */
    public function listAccount()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            $where = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $tab_status = $this->request->param('status/d', 1);

            $where = $this->_where_listAccount($where);

            switch ($tab_status) {
                case 1:
                    $where[] = ['ogp.status', '=', 1140];
                    break;
                case 2:
                    $where[] = ['ogp.status', '=', 1200];
                    break;
            }
            switch ($tab_status) {
                case 1:
                case 2:
                    $list = db('order_outgo_order_group ogp')
                        ->field('ogp.*
                         ,ft.name as ft_name ,g.name as ft_group_name
                         ,count(ooor.id) as order_count
                         ,sum(ooor.after_return_price) as sum_after_return_price
                         ,sum(ooor.other_cut_payment) as sum_other_cut_payment
                         ,su.username
                        ')
                        ->join('order_outgo_order ooor', "ogp.id=ooor.order_outgo_order_group_id", 'left')
                        ->join('order o', "o.id=ooor.order_id", 'left')
                        ->join('factory ft', "ft.id=ooor.factory_id", 'left')
                        ->join('group g', 'g.id=ooor.factory_child_id', 'left')
                        ->join('system_user su', 'su.id=ogp.admin_id_submit', 'left')
                        ->where($where)
                        ->page($page)->limit($limit)->orderRaw('ogp.id desc')
                        ->group('ogp.id desc')
                        ->select();
                    foreach ($list as $k => $v) {
                        if (intval($v['id']) == 0) {
                            unset($list[$k]);
                            continue;
                        }
                        $list[$k]['time_submit'] = date('Y-m-d H:i:s', $list[$k]['time_submit']);
                        $list[$k]['time_payment'] = date('Y-m-d H:i:s', $list[$k]['time_payment']);
                        $list[$k]['status_account'] = '待结算';
                        switch ($v['status']) {
                            case '1200':
                                $list[$k]['status_account'] = '已结算';
                                break;
                        }
                    }
                    $count = db('order_outgo_order_group ogp')
                        ->field('ogp.*
                         ,ft.name as ft_name ,g.name as ft_group_name
                         ,count(ooor.id) as order_count
                         ,sum(ooor.after_return_price) as sum_after_return_price
                         ,sum(ooor.other_cut_payment) as sum_other_cut_payment
                        ')
                        ->join('order_outgo_order ooor', "ogp.id=ooor.order_outgo_order_group_id", 'left')
                        ->join('order o', "o.id=ooor.order_id", 'left')
                        ->join('factory ft', "ft.id=ooor.factory_id", 'left')
                        ->join('wx_group g', 'g.id=ooor.factory_child_id', 'left')
                        ->where($where)->count();
                    break;
            }
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list,
                'count' => $count,
                'status' => $tab_status,
                'statData' => $this->_get_statData_listAccount(),
            ];
            return json($result);
        }
        $statData = [
            1 => db('order_outgo_order_group ogp')
                ->where([
                    ['ogp.status', '=', 1140]
                ])
                ->count(),
            2 => db('order_outgo_order_group ogp')
                ->where([
                    ['ogp.status', '=', 1200]
                ])
                ->count(),
        ];
        $assign = [
            'status' => 1,
            'statData' => $statData,
            'stallsKV' => ['0' => '请选择'],
            'clientStatus' => config('mimo.client_status'),
            'factory_ids' => $this->_factiory_xm_select(),
        ];
        return $this->assign($assign)->fetch();
    }

    private function _get_statData_listAccount()
    {
        $where_temp = [];
        //订单加一级
        order_level($where_temp, 'o.');
        $statData = [
            1 => db('order_outgo_order_group ogp')
                ->join('order_outgo_order ooor', "ooor.order_outgo_order_group_id=ogp.id", 'left')
                ->join('order o', "ooor.order_id=o.id", 'left')
                ->where([
                    ['ogp.status', '=', 1140]
                ])
                ->where($where_temp)
                ->group('ogp.id')
                ->count(),
            2 => db('order_outgo_order_group ogp')
                ->join('order_outgo_order ooor', "ooor.order_outgo_order_group_id=ogp.id", 'left')
                ->join('order o', "ooor.order_id=o.id", 'left')
                ->where([
                    ['ogp.status', '=', 1200]
                ])
                ->where($where_temp)
                ->group('ogp.id')
                ->count(),
        ];
        return $statData;
    }

    private function _where_listAccount($where)
    {
        //订单加一级
        order_level($where, 'o.');
        $tab_status = $this->request->param('status/d', 1);
        $factory_ids = $this->request->param('factory_ids/s', '');
        $createDateRange = $this->request->param('create_date_range/s');
        if (trim($factory_ids) != '') {
            $where[] = ['ogp.factory_child_id', 'in', $factory_ids];
        }
        if ($createDateRange != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
            switch ($tab_status) {
                case 1:
                    $where[] = ['ogp.time_submit', 'between', [$startTime, $endTime + 86399]];
                    break;
                case 2:
                    $where[] = ['ogp.time_payment', 'between', [$startTime, $endTime + 86399]];
                    break;
            }
        }
        return $where;
    }

    /**
     * 外发管理》委外结算  已付款
     * @date 2021/12/27
     * @author zhuguosen 905502314@qq.com
     */
    public function accountPayment()
    {
        //1,参数处理
        $ids = $this->request->param('id', []);
        foreach ($ids as $k => $id) {
            $ids[$k] = intval($id);
        }
        Db::startTrans();
        try {
            //2,业务->wx_order_outgo_order_group表修改
            $grSelect = db('order_outgo_order_group ogp')
                ->field('ogp.id ,ogp.factory_id ,ogp.factory_child_id
                ')
                ->where([
                    ['ogp.id', 'in', $ids],
                    ['ogp.status', '=', 1140],
                ])->select();
            if (count($grSelect) == 0) {
                Db::rollback();
                return $this->Json(10, '失败');
            }
            $temp = db('order_outgo_order_group')
                ->where([
                    ['id', 'in', $ids],
                    ['status', '=', 1140],
                ])->update([
                    'status' => 1200,
                    'time_payment' => time(),
                    'admin_id_payment' => ADMIN_ID,
                    'update_time' => time(),
                ]);
            if ($temp != count($ids)) {
                Db::rollback();
                return $this->Json(11, '失败');
            }
            //3,业务->order_outgo_order表修改
            foreach ($grSelect as $k => $v) {
                $count = db('order_outgo_order')->where([
                    ['factory_id', '=', $v['factory_id']],
                    ['factory_child_id', '=', $v['factory_child_id']],
                    ['status', '=', 1140],
                ])->count();
                $temp = db('order_outgo_order')->where([
                    ['factory_id', '=', $v['factory_id']],
                    ['factory_child_id', '=', $v['factory_child_id']],
                    ['status', '=', 1140],
                ])->update([
                    'status' => 1200,
                    'update_time' => time(),
                    'admin_id_1200' => ADMIN_ID,
                    'time_update_1200' => time(),
                ]);
                if ($temp != $count) {
                    Db::rollback();
                    return $this->Json(12, '失败', $temp);
                }
            }
            //4,业务log->暂无
            //5,成本->暂无
            //6,财务->暂无
            //7,经验->暂无
            Db::commit();
            return $this->json(1, '成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->json(100, '失败');
        }
    }

    /**
     * 导出
     *
     */
    private function _exportXls($title, &$list)
    {
        $params = [];
        $data = [];
        foreach ($list as $k => $v) {
            $data[] = [
                $v['is_auto_import_name'],
                $v['client_ordernum'],
                $v['sku'],
                "{$v['ft_name']}/{$v['ft_group_name']}",
                $v['sum_shicai_count'],
                $v['group_out_type_txt'],
//                $v['order_price'],
                $v['cost_little'],
                $v['group_unit_price'],
                $v['order_price_res'],
                $v['caichuang_t_strip_price'],
                $v['sum_jiaohuo_count'],
                $v['sum_jiaohuo_tail_count'],
                $v['sum_store_count'],
                $v['chayi_num'],
                $v['price_all'],
                $v['confiscation_num'],
                $v['after_return_time'],
                $v['after_return_price'],
                $v['other_cut_payment'],
                $v['remark'],
                $v['status_txt'],
            ];
        }
        $params['file'] = $title;
        $params['sheet'] = [
            [
                'head' => ['来源', '订单号', 'SKU', '委外工厂', '裁床数', '委外类型', '小计', '委外倍率', '委外单价', '捆条金额', '车间总数', '尾部总数', 'MES入仓总数', '差异数', '加工费总金额', '没收', '工时', '返工金额', '其它扣款', '备注', '状态'], // 表头
                'data' => $data,
            ],
        ];
        unset($list);
        plugins_run('excel/excel/export', $params);
    }

    /**
     * 外发管理》进度报表
     */
    public function reportList()
    {
        if ($this->request->isAjax()) {
            $where = [
                ['ft.type', '=', 1],
                ['oot.status', '>=', 200],
            ];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);

            $where = $this->_where_reportList($where);

            $order = "oot.update_time desc";
            $list = db('order o')
                ->field('
                oot.*
                ,o.client_ordernum,o.sku,o.shipment_time,o.order_price,o.caichuang_over_time,o.is_auto_import
                 ,oext.cost_little
                 ,s.pic,s.ori_pic
                 ,ft.name as ft_name ,g.name as ft_group_name
                   ,ft2.name as ft2_name ,g2.name as ft2_group_name
                 ,g.unit_cutting,g.unit_workshop,g.unit_tail,g.unti_manual,g.unit_time_price
                 ')
                ->join('order_ext oext', "o.id=oext.order_id", 'left')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('factory ft2', "ft2.id=oot.after_factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
//                ->join('order_material om ', 'om.order_id=o.id', 'left')
                ->join('wx_group g', 'oot.group_id=g.id', 'left')
                ->join('wx_group g2', 'oot.after_group_id=g2.id', 'left')
                ->where($where)
                ->page($page)->limit($limit)->orderRaw($order)
//                ->group('om.order_id')
                ->select();
            $count = db('order o')
                ->join('order_ext oext', "o.id=oext.order_id", 'left')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('factory ft2', "ft2.id=oot.after_factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('wx_group g', 'oot.group_id=g.id', 'left')
                ->join('wx_group g2', 'oot.after_group_id=g2.id', 'left')
                ->where($where)
                ->count();
            $list = $this->_deal_with_reportList($list);
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list,
                'count' => $count,
            ];
            return json($result);
        }
        $assign = [
            'factory_ids' => $this->_factiory_xm_select(),
            'group_out_type_select' => [
                0 => '请选择',
                2 => '车间',
                3 => '尾部',
                4 => '专机',
            ],
            'status_select' => [
                0 => '请选择',
                200 => '车缝中',
                300 => '后整中',
                301 => '已退货',
                302 => '外协尾部',
                1000 => '已完成',
            ],
        ];
        return $this->assign($assign)->fetch();
    }

    private function _where_reportList($where)
    {
        //订单加一级
        order_level($where, 'o.');
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $sku = $this->request->param('sku/s', '');
        $time_send_0_date_range = $this->request->param('time_send_0_date_range/s');
        $time_return_0_date_range = $this->request->param('time_return_0_date_range/s');
        $isAutoImport = $this->request->param('is_auto_import/d', 0);
        $factory_ids = $this->request->param('factory_ids/s', '');
        $status = $this->request->param('status/d', 0);
        $group_out_type = $this->request->param('group_out_type/d', 0);
        if ($clientOrdernum != '') {
            $where[] = ['o.client_ordernum', 'like', "%" . $clientOrdernum . "%"];
        }
        if ($sku != '') {
            $where[] = ['o.sku', 'like', "%" . $sku . "%"];
        }
        if ($isAutoImport > 0) {
            $where[] = ['o.is_auto_import', '=', $isAutoImport];
        }
        if (trim($factory_ids) != '') {
            $where[] = ['oot.group_id', 'in', $factory_ids];
        }
        if ($time_send_0_date_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $time_send_0_date_range));
            $where[] = ['oot.time_send_0', 'between', [$startTime, $endTime + 86399]];
        }
        if ($time_return_0_date_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $time_return_0_date_range));
            $where[] = ['oot.time_return_0', 'between', [$startTime, $endTime + 86399]];
        }
        if ($status > 0) {
            $where[] = ['oot.status', '=', $status];
        }
        if ($group_out_type > 0) {
            $where[] = ['oot.after_out_type', 'like', "%" . $sku . "%"];
        }
        return $where;
    }

    private function _deal_with_reportList($list)
    {
        foreach ($list as $k => $v) {
            //来源
            $list[$k]['is_auto_import_name'] = arrayGet(config('mimo.order_from'), $v['is_auto_import'], '');
            $list[$k]['shipment_time'] = intval($list[$k]['shipment_time']) <= 0 ? '' : date('m-d', $list[$k]['shipment_time']);
            $list[$k]['caichuang_over_time'] = intval($list[$k]['caichuang_over_time']) <= 0 ? '' : date('Y-m-d H:i', $list[$k]['caichuang_over_time']);
            $list[$k]['hope_shipment_time'] = intval($list[$k]['hope_shipment_time']) <= 0 ? '' : date('Y-m-d H:i', $list[$k]['hope_shipment_time']);
            $list[$k]['time_send_2'] = intval($list[$k]['time_send_2']) <= 0 ? '' : date('Y-m-d H:i', $list[$k]['time_send_2']);
            $list[$k]['time_return_1'] = intval($list[$k]['time_return_1']) <= 0 ? '' : date('Y-m-d H:i', $list[$k]['time_return_1']);
            $list[$k]['time_return_2'] = intval($list[$k]['time_return_2']) <= 0 ? '' : date('Y-m-d H:i', $list[$k]['time_return_2']);
            $time_send_0_time_return_0 = intval($list[$k]['time_return_0']) - intval($list[$k]['time_send_0']);
            $secsToStr = $this->secsToStr($time_send_0_time_return_0);
            $list[$k]['time_send_0_time_return_0'] = "{$secsToStr['day']}天{$secsToStr['hour']}时{$secsToStr['minute']}分";
            $list[$k]['time_send_0'] = intval($list[$k]['time_send_0']) <= 0 ? '' : date('Y-m-d H:i', $list[$k]['time_send_0']);
            $list[$k]['time_return_0'] = intval($list[$k]['time_return_0']) <= 0 ? '' : date('Y-m-d H:i', $list[$k]['time_return_0']);
            $list[$k]['after_out_type_txt'] = '';
            switch ($v['after_out_type']) {
                case 2:
                    $list[$k]['after_out_type_txt'] = '车间';
                    break;
                case 3:
                    $list[$k]['after_out_type_txt'] = '尾部';
                    break;
                case 4:
                    $list[$k]['after_out_type_txt'] = '专机';
                    break;
                case '3,4':
                case '4,3':
                    $list[$k]['after_out_type_txt'] = '尾部,专机';
                    break;
            }
            $list[$k]['status_txt'] = '车缝中';
            switch ($v['status']) {
                case 200:
                    $list[$k]['status_txt'] = '车缝中';
                    break;
                case 300:
                    $list[$k]['status_txt'] = '后整中';
                    break;
                case 301:
                    $list[$k]['status_txt'] = '已退货';
                    break;
                case 302:
                    $list[$k]['status_txt'] = '外协尾部';
                    break;
                case 1000:
                    $list[$k]['status_txt'] = '已完成';
                    break;
            }
            $osList = (new OrderSizeService())->getListByOrderId($v['order_id']);
            ////总数：<span title="总下单数">{{ d.osStat.order_count }}</span>/<span title="总裁床数">{{ d.osStat.shicai_count }}</span>/<span title="总车间数">{{ d.osStat.jiaohuo_count }}</span>/<span title="总后整数">{{ d.osStat.jiaohuo_tail_count }}</span>/<span title="总打包数">{{ d.osStat.delivery_count }}</span>/<span title="总出货数">{{ d.osStat.daohuo_count }}</span>
            $list[$k]['sum_shicai_count'] = array_sum(array_column($osList, 'shicai_count'));
            $list[$k]['sum_jiaohuo_count'] = array_sum(array_column($osList, 'jiaohuo_count'));
            $list[$k]['sum_jiaohuo_tail_count'] = array_sum(array_column($osList, 'jiaohuo_tail_count'));
            $list[$k]['sum_store_count'] = array_sum(array_column($osList, 'store_count'));
            //差异数
            $list[$k]['chayi_num'] = $list[$k]['sum_store_count'] - $list[$k]['sum_shicai_count'];

            //group_unit_price 委外倍率 =
            $list[$k]['group_unit_price'] = 0;
            switch ($v['after_out_type']) {
                default:
                    $v['unit_workshop'] > 0 && $list[$k]['group_unit_price'] = $v['unit_workshop'];
                    $v['unit_tail'] > 0 && $list[$k]['group_unit_price'] = $v['unit_tail'];
                    $v['unti_manual'] > 0 && $list[$k]['group_unit_price'] = $v['unti_manual'];
                    break;
            }
            //委外单价
            $list[$k]['order_price_res'] = sprintf("%.2f", $v['cost_little'] * $list[$k]['group_unit_price']);
            //返工金额
            $list[$k]['after_return_price'] = sprintf("%.2f", $v['unit_time_price'] * $v['after_return_time']);
            //退货回货/外协回货  查询
            $list[$k]['return_fr_num'] = 0;
            $list[$k]['return_ot_num'] = 0;
            $temp = db("order_outgo_action_log")
                ->field('type,return_goods_num')
                ->where([
                    ['order_id', '=', $v['order_id']],
                    ['type', 'in', ['finishReturn_confirmReturnGoods', 'outgoTail_confirmReturnGoods']],
                ])->orderRaw('id desc')->limit(2)->select();
            foreach ($temp as $k2 => $v2) {
                $v2['type'] == 'finishReturn_confirmReturnGoods' && $list[$k]['return_fr_num'] = $v2['return_goods_num'];
                $v2['type'] == 'outgoTail_confirmReturnGoods' && $list[$k]['return_ot_num'] = $v2['return_goods_num'];
            }
        }
        return $list;
    }

    /**
     * 秒数转 天 时 分
     * @param int $secs
     * @return array
     */
    private function secsToStr($secs)
    {
        $result = array(
            'day' => 0,
            'hour' => 0,
            'minute' => 0,
            'second' => 0,
        );
        if ($secs >= 86400) {
            $days = floor($secs / 86400);
            $secs = $secs % 86400;
            $result['day'] = $days;
        }
        if ($secs >= 3600) {
            $hours = floor($secs / 3600);
            $secs = $secs % 3600;
            $result['hour'] = $hours;
        }
        if ($secs >= 60) {
            $minutes = floor($secs / 60);
            $secs = $secs % 60;
            $result['minute'] = $minutes;
        }
        $result['second'] = $secs;
        return $result;
    }

    /**
     * 外发管理》进度报表>统计数据
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/11
     */
    public function otherReportListData()
    {
        $where = [
            ['ft.type', '=', 1],
            ['oot.status', '>=', 200],
        ];
        $where = $this->_where_reportList($where);
        $list = db('order o')
            ->field('count(distinct o.id) as sum_order_id
            ,sum(os.order_count) as sum_order_count
            ,sum(os.shicai_count) as sum_shicai_count
            ,sum(os.jiaohuo_count) as sum_jiaohuo_count
            ,sum(os.jiaohuo_tail_count) as sum_jiaohuo_tail_count
            ,sum(os.store_count) as sum_store_count
                 ')
            ->join('order_ext oext', "o.id=oext.order_id", 'left')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('factory ft2', "ft2.id=oot.after_factory_id", 'left')
            ->join('sku s', "o.sku=s.sku", 'left')
//                ->join('order_material om ', 'om.order_id=o.id', 'left')
            ->join('wx_group g', 'oot.group_id=g.id', 'left')
            ->join('wx_group g2', 'oot.after_group_id=g2.id', 'left')
            ->join('order_size os', "o.id=os.order_id", 'left')
            ->where($where)
            ->find();
        $list2 = db('order o')
            ->field("
            sum(if(lg.type='finishReturn_confirmReturnGoods',lg.return_goods_num,0)) as return_fr_num
            , sum(if(lg.type='outgoTail_confirmReturnGoods',lg.return_goods_num,0)) as return_ot_num
                 ")
            ->join('order_ext oext', "o.id=oext.order_id", 'left')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('factory ft2', "ft2.id=oot.after_factory_id", 'left')
            ->join('sku s', "o.sku=s.sku", 'left')
//                ->join('order_material om ', 'om.order_id=o.id', 'left')
            ->join('wx_group g', 'oot.group_id=g.id', 'left')
            ->join('wx_group g2', 'oot.after_group_id=g2.id', 'left')
            ->join('order_outgo_action_log lg', "o.id=lg.order_id and lg.type in ('finishReturn_confirmReturnGoods','outgoTail_confirmReturnGoods')", 'left')
            ->where($where)
            ->find();
        return $this->json(1, '', $list + $list2);
    }
}